<template>
  <div class="personnel-container w-100P h-100P flex-column">
    <div class=" justify-between w-100P search-tab bg-w ">
      <el-form ref="QueryInfo" inline :model="page" class="demo-form-inline ">
        <el-form-item label="组织名称" prop="keyword">
          <el-input v-model="page.keyword" class="input-width" placeholder="请输入组织名称" />
        </el-form-item>
        <!-- <el-form-item label="组织状态" prop="status">
          <el-input v-model="queryInfo.status" class="input-width" placeholder="请输入组织状态" />
        </el-form-item> -->
      </el-form>
      <div class="flex-row search-button-bar">
        <el-button type="info" @click="handleOrgSearch">查询</el-button>
        <el-button @click="handleResetQuery">重置</el-button>
      </div>
    </div>
    <div class="add-button  bg-w">
      <el-dropdown trigger="click" @command="handleCommand" placement="bottom-start">
        <el-button class="custom-button">
          新增
          <i class="el-icon-arrow-down el-icon--left" />
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="Peer">添加同级组织</el-dropdown-item>
          <el-dropdown-item command="Sub">添加子组织</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>

    <div class="flex-sub table-content bg-w">
      <el-table
        :data="tableData"
        header-cell-class-name="table-header-cell"
        header-row-class-name="table-header-row"
        row-key="id"
        height="98%"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        highlight-current-row
        @current-change="selTable"
      >
        <el-table-column prop="name" label="组织名称" />
        <el-table-column prop="sortNo" label="排序" />
        <el-table-column prop="dataStatusName" label="状态" />
        <el-table-column label="创建时间">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime | dateTimeFormatter }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          fixed="right"
          :width="handleScreenWidthToVw(150)+'px'"
          align="center"
        >
          <div slot-scope="scope">
            <span size="small" class="btn-edit" @click="change(scope.row)">修改</span>
            <span class="lh-23">|</span>
            <span class="btn-delete " @click="delOrg(scope.row.id)">删除</span>
          </div>
        </el-table-column>
      </el-table>
    </div>

    <!-- <el-pagination
      hide-on-single-page
      background
      layout="total,prev, pager, next, jumper"
      :current-page="page.pageNo"
      :page-size="page.pageSize"
      :total="page.total"
      class=" pagination"
      @current-change="handleCurrentChange"
    /> -->

    <el-dialog
      :title="formInfo.title"
      :before-close="cancelForm"
      :visible.sync="addDepdialogVisible"
      :width="handleScreenWidthToVw(574)+'px'"
      :close-on-click-modal="false"
    >
      <el-form
        ref="orgForm"
        :model="form"
        :label-width="handleScreenWidthToVw(120)+'px'"
        :rules="Rules"
      >
        <el-form-item label="上级组织：">
          <span>{{ formInfo.pidName }}</span>
        </el-form-item>

        <el-form-item label="组织名称：" prop="name">
          <el-input v-model="form.name" placeholder="请输入组织名称" class="input-width" />
        </el-form-item>

        <el-form-item label="显示排序：">
          <el-input-number
            v-model="form.sortNo"
            controls-position="right"
            :min="0"
            class="input-width"
          />
        </el-form-item>

        <el-form-item label="组织状态：">
          <el-radio v-model="form.dataStatusEnum" label="NORMAL">正常</el-radio>
          <el-radio v-model="form.dataStatusEnum" label="STOP">停用</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <SubButton @subClick="updateData" />
        <CancelButton @cancelClick="cancelForm" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getOrglist, delOrgList, addOrglist, findOrgList, updateOrglist } from './api'
import { tree } from '@/utils/tree'
import { Message } from 'element-ui'
import { MAX_INTEGER } from '@/consts'
import SubButton from '@/components/sub-button/index.vue'
import CancelButton from '@/components/cancel-button/index.vue'

import { handleScreenWidthToVw } from '@/utils/tools'

export default {
  components: { SubButton, CancelButton },
  data() {
    return {
      addDepdialogVisible: false,
      form: {
        dataStatusEnum: 'NORMAL',
        name: '',
        pid: 0,
        sortNo: 0,
      },
      page: {
        pageNo: 1,
        pageSize: MAX_INTEGER,
        keyword: '',
        total: null,
      },
      // option: [],
      tableData: [],
      formInfo: { selDep: null, title: '', pidName: null },
    }
  },
  computed: {
    handleScreenWidthToVw() {
      return handleScreenWidthToVw
    },
    buttonTitle() {
      return this.formInfo.title === '修改' ? '修改' : '新增'
    },
    Rules() {
      return {
        name: [
          { required: true, message: '请输入组织名称', trigger: 'blur' },
          // { min: 1, max: 10, message: "长度不超过 10 个字符", trigger: "blur" },
        ],
      }
    },
  },
  created() {
    this.getData()
  },
  watch: {
    page: {
      deep: true,
      handler(newval) {
        this.getData()
      },
    },
  },
  methods: {
    // 检索重置
    handleResetQuery() {
      this.page.keyword = ''
      this.getData()
    },
    // 组织关键字检索
    async handleOrgSearch() {
      const data = await findOrgList(this.page)
      this.tableData = tree(data)
    },
    // 切换页面
    // handleCurrentChange(val) {
    //   this.page.pageNo = val
    //   this.getData(this.page)
    // },
    // 选择新增菜单类型
    handleCommand(command) {
      if (command === 'Peer') {
        this.addPeer()
      } else {
        this.addSubordinate()
      }
    },
    // 重置表单
    resetFrom() {
      this.form = {
        dataStatusEnum: 'NORMAL',
        name: '',
        pid: 0,
        sortNo: 0,
      }
    },
    // 表单取消按钮
    cancelForm() {
      this.resetFrom()
      this.$refs.orgForm.clearValidate()
      this.addDepdialogVisible = false
    },
    // 表格中选中组织
    selTable(val) {
      this.formInfo.selDep = val
    },
    // 修改组织
    change(dep) {
      this.formInfo.title = '修改'
      this.formInfo.pidName = dep.pid === '0' ? '无上级' : this.findAllOrg(dep.pid)
      Object.assign(this.form, dep)
      this.addDepdialogVisible = true
    },
    // 新增同级按钮
    addPeer() {
      this.formInfo.title = '新增同级'
      if (!this.formInfo.selDep) {
        Message.error('请先选择组织')
      } else if (this.formInfo.selDep.id === this.tableData[0].id) {
        Message.error('权利不足，不能建立同级组织')
      } else if (this.formInfo.selDep.pid) {
        this.form.pid = this.formInfo.selDep.pid
        this.formInfo.pidName =
          this.formInfo.selDep.pid === '0' ? '无上级' : this.findAllOrg(this.formInfo.selDep.pid)
        this.addDepdialogVisible = true
      }
    },
    // 新增下级按钮
    addSubordinate() {
      if (this.formInfo.selDep) {
        this.formInfo.title = '新增下级'
        this.formInfo.pidName = this.formInfo.selDep.name
        this.form.pid = this.formInfo.selDep.id
        this.addDepdialogVisible = true
      } else {
        Message.error('请先选择组织')
      }
    },
    // 检索上级组织
    findAllOrg(pid) {
      var hasFound = false // 表示是否有找到id值
      var result = null
      var fn = function (data) {
        if (Array.isArray(data) && !hasFound) {
          // 判断是否是数组并且没有的情况下，
          data.forEach(item => {
            if (item.id === pid) {
              // 数据循环每个子项，并且判断子项下边是否有id值
              result = item // 返回的结果等于每一项
              hasFound = true // 并且找到id值
            } else if (item.children) {
              fn(item.children) // 递归调用下边的子项
            }
          })
        }
      }
      fn(this.tableData) // 调用一下
      return result ? result.name : '无上级'

      // return depOrg ? depOrg.name : '无上级'
    },
    // 删除组织
    delOrg(orgId) {
      this.$confirm('此操作将永久删除该组织, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
        .then(() => {
          delOrgList(orgId)
            .then(() => {
              this.getData()
              this.$message({
                type: 'success',
                message: '删除成功!',
              })
            })
            .catch(e => {})
        })
    },
    //更新数据
    async updateData() {
      await this.$refs.orgForm.validate()
      this.formInfo.title === '修改' ? await updateOrglist(this.form) : await addOrglist(this.form)
      this.resetFrom()
      this.getData()
      this.addDepdialogVisible = false
      this.$message({
        type: 'success',
        message: this.formInfo.title + '成功!',
      })
    },
    // 获取列表数据
    async getData() {
      const res = await getOrglist()
      this.tableData = res
      // this.option = records
      // this.tableData = tree(records)
      // this.page.total = total
    },
  },
}
</script>

<style lang="scss" scoped>
.personnel-container {
  background-color: #f3f4f8;
}

.bg-w {
  background-color: white;
}

.search-tab {
  padding: vh(20px) vw(20px) 0 vw(20px);
  margin-bottom: vh(20px);
}

.add-button {
  padding: vh(20px) vw(20px);
}

.table-content {
  padding: vh(20px) vw(20px);
}

.search-button-bar {
  height: vh(40px);
  margin-top: vh(2px);
}

.dialog-input-width {
  width: vw(180px);
  font-size: vw(14px);
}

.btn-edit {
  margin-right: vw(10px);
  color: #0084ee;

  &:hover {
    cursor: pointer;
    opacity: 0.7;
  }
}

.btn-delete {
  margin-left: vw(10px);
  color: #d12d1f;

  &:hover {
    cursor: pointer;
    opacity: 0.7;
  }
}

::v-deep {
  .el-button {
    font-size: vw(14px);
  }

  .custom-button {
    padding: vw(10px) vw(20px);
    font-size: vw(14px);
    background: #f2f2f2;
  }

  .el-dialog__header {
    height: vh(52px);
    padding: vw(17px) vh(23px) vw(17px);
    // background-color: #f8f8f8;
  }

  .el-dialog__title {
    font-size: vh(18px);
    font-weight: 500;
    color: #333;
  }

  .el-dialog__body {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    padding: vh(20px) 0;
  }

  .el-dialog__footer {
    padding: vh(10px) vw(20px) vh(20px);
    // background: #f0f4f8;
    text-align: center;
  }

  .el-form-item {
    margin-bottom: vh(22px);
  }

  .el-form-item__label {
    font-size: vw(14px);
    line-height: vh(40px);
  }

  .el-form-item__content {
    font-size: vw(14px);
    line-height: vh(40px);
  }

  .input-width {
    width: vw(250px);
    font-size: vw(14px);
  }

  .el-icon--left {
    margin-right: 0;
  }

  .el-radio__label {
    font-size: vh(14px);
  }

  .el-input-number {
    line-height: vh(28px);
  }

  .el-table td,
  .el-table th {
    padding-left: vw(20px);
  }

  .el-input-number__decrease,
  .el-input-number__increase {
    width: vw(40px);
    height: vh(16px) !important;
    line-height: vh(16px) !important;
  }
}
</style>
